package com.dxt.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxt.common.*;
import com.dxt.message.ReponseMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@Service("getService")
public class GetService extends IBaseBusiService {
    private static final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());

    @Autowired
    CacheManager cacheManager;

    @Override
//    @Transactional
    public ReponseMessage execute(String reqInfo, String url) {
        logger.debug(LogHelper._FUNC_START_());
        ReponseMessage message = new ReponseMessage();

        String response = null;
        try {
            response = HttpUtil.getHttpGetResponse(url+"?1=1",
                    cacheManager.getSysConfigByCode(AppConstant.SYS_CONFIG_KEY.KEY_TOKEN),reqInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("response="+response);
        JSONObject jsonObj = null;

        if(StringUtils.isNotBlank(response)){
            jsonObj = JSON.parseObject(response);
        }
        JSONObject retObject = new JSONObject();
        if(jsonObj != null) {
            try{
                String code = jsonObj.getString(AppConstant.REQUEST_REPONSE_PARAM.PARAM_OUT_CODE);
                String respMessage = java.net.URLDecoder.decode(StringUtils.stripToEmpty(jsonObj.getString(AppConstant.REQUEST_REPONSE_PARAM.PARAM_OUT_MESSAGE)), "UTF-8");
                Boolean success = jsonObj.getBoolean(AppConstant.REQUEST_REPONSE_PARAM.PARAM_OUT_SUCCESS);
                Long timestamp = jsonObj.getLong(AppConstant.REQUEST_REPONSE_PARAM.PARAM_OUT_TIMESTAMP);
                String result = jsonObj.getString(AppConstant.REQUEST_REPONSE_PARAM.PARAM_OUT_RESULT);
                if(StringUtils.isNotBlank(result)){
                    message.setMsg(AppConstant.REPONSE_CODE.SUCCESS_CODE,
                            AppConstant.REPONSE_MSG.SYS_REQUEST_OK_MSG, result, success, timestamp);
                }else{
                    if(StringUtils.isNotBlank(code)){
                        message.setMsg(code,respMessage,success,timestamp);
                    }else{
                        message.setMsg(AppConstant.REPONSE_CODE.BUSI_WARNING,AppConstant.REPONSE_MSG.SYS_EMPTY_MSG,
                                success,timestamp);
                    }
                }
            }catch(UnsupportedEncodingException e){
                e.printStackTrace();
                message.setMsg(AppConstant.REPONSE_CODE.SYS_ERROE,AppConstant.REPONSE_MSG.SYS_ERROR_MSG,e.getMessage());
            }

        }
        return message;
    }

}
